/* 
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/********** Variable local ***********/
//adresse service web
var adress = "https://localhost/GWIT_Plateform_Trading/web/app_dev.php/";

/***** initialisation des éléments *******/
$("#check-login-load").append("<img src='/GWIT_Plateform_Trading/web/loading/image/valide2.png'/>");
//on initialise les bouttons previous et next
$("#previous-desktop").attr('class','disabled');
$("#previous-desktop a").html('&larr; Prev.');
$("#next-desktop").attr('class', 'next');
//alert(listOfDesktop[0].hash);
$("#next-desktop a").html('Next &rarr;');

//console.log($().();
//fin de chargement de l application
$("#check-appli-load").append("<img src='/GWIT_Plateform_Trading/web/loading/image/valide2.png'/>");


//TODO : Question de sécurité sur l'envoi de donnée a revoir'
$.ajaxSetup({async:false});

//Chargement des moniteurs
$.get(adress+"monitor/getUserMonitor",function(data){
    $(data).each(function(){
        $("#desktop-grpe").monitor_add_menu(this.name, this.id);
        $("#center").monitor_add_layout(this.name, this.id);
        //console.log("pit stop 1");
    });
}, "json");

//Chargement des widgets
$.get(adress+"widget/getUserWidget",function(data){
    $(data).each(function(){
        console.log(this);
        //Chargement du menu
        $("#widget-grpe").widget_add_menu(this.name, this.monitorid, this.id);
        //Ajout du widget dans le monitor
        $("#center div[m-id='"+this.monitorid+"'] div div.widget_zone").widget_add_layout(this.name, this.monitorid, this.id);
        //Ajuster les paramètres css
        console.log("ça passe");
        setCss(this.id, this.coordx, this.coordy, this.width, this.height, this.position);
    });
}, "json");

$.ajaxSetup({async:true});


//console.log($("#monitor_menu").find("span").text());
//console.log($("#desktop-grpe li").length);
//console.log($('#desktop-grpe li, a').get(0) === $('#desktop-grpe li, a').get(0));
/***********************************************************************************************************/
var myLayout; // a var is required because this page utilizes: myLayout.allowOverflow() method

myLayout = $('body').layout(layout_Outer_body).allowOverflow('north');
//console.log("pit stop 2");
//Modification Initialisation des monitors
$('div .container_page').each(function(){
    $(this).layout(layout_Outer_container);
});//layout_Outer_containe

//myLayoutWidget = $('div .widget').layout(layout_Outer_widget);//layout_Outer_containe
//
//quit la page de chargement, le delai laissera de la marge au serveur

setTimeout(
    function()
    {
        $("#shadowing-loader").hide("slow");
        $("#box-loader").hide("slow");
    }, 500);
    
$("#check-perso-load").append("<img src='/GWIT_Plateform_Trading/web/loading/image/valide2.png'/>");

/********** Event window ************/
/*
$('.widget').draggable({ 
        handle: ".modal-header",
        containment: "parent",
        scroll: false
});

$('.widget').resizable({
        maxHeight: 700,
        maxWidth: 800,
        minHeight: 30,
        minWidth: 400
});

$('.widget').resize(function() {
            if (myLayoutWidget) myLayoutWidget.resizeAll();
});
*/
/* Minimize: Hide content of Widget */
$('.widget .modal-header .btn-group .toggle_button').on("click", function() {
        /*var this_obj = $(this);
        var icone = this_obj.children();
        var widget_body = this_obj.parent().parent().parent().find('.widget-body');
        if(icone.hasClass('icon-minus')){
                icone.removeClass('icon-minus').addClass('icon-plus');
                //this_obj.parent().parent().parent().children('.ui-layout-center').hide();
                this_obj.parent().parent().parent().height(25);
        }else{
                icone.removeClass('icon-plus').addClass('icon-minus');
                this_obj.parent().parent().parent().height(200);
        }

        this_obj.find('div .ui-resizable-handle').hide();
        */

});

/* HIDE/SHOW Widget */
$('.widget .modal-header .btn-group .hide_button').on("click", function() {
        var this_obj = $(this);
});

$(".widget").on("mousedown", function() {
        $('.widget').removeClass('on_top');
        $(this).addClass('on_top');
});

/*************** MAIN MENU ****************/
/* Monitor */
$(".dropdown_button").on({
    click:  function(){
            $(this).toggleClass("open");
    }
});


/* Widget */
$(".widget_button").on({
    click: function(){
            /*Close ul*/
            $(this).parent().toggleClass("open");


    }
});
$("#widget_menu li.under_menu").on({
    click: function(){
            /*Close ul*/
            $(this).parent().parent().toggleClass("open");
    }
});


/* Activate/Hide widget */
$("#widget_menu li.wiget_list a").live({
    click: function(){

            $("#widget_menu li.wiget_list a div.btn").on({
                click: function(event){
                        event.stopPropagation();
                }
            });

        /*    HIDE/SHOW widget    */
        var WidgetContainer = $('#monitor_1 .widget_zone > div');

        //Show Widget and put it on the front (z-index maximum)
        if($(this).children(".icon-ok").hasClass('icon-white')){ 
                $(this).children(".icon-ok").removeClass('icon-white');
                var selector = $(this).attr();
                WidgetContainer.filter(this.hash).show();
        }else{//Hide Widget
                $(this).children(".icon-ok").addClass('icon-white');
                WidgetContainer.filter(this.hash).hide();
        }
    }
});

/* Button Ajouter un widget */
$("#widget_menu li.under_menu a").on({click: function(){
    $("#lightbox-add-widget div#shadowing").show();
    $("#lightbox-add-widget div#box").show();
    $("#lightbox-add-widget").unbind("click");
    //Id monitor : NB. Current desktop est utilisé dans les monitors
    var idmonitor = $($("#monitor_menu div li.li_grey").get(indexCurrentDesktop)).attr('m-id');
    console.log($($("#monitor_menu div li.li_grey").get(indexCurrentDesktop)).attr('m-id'));
    //Ajout du widget dans le menu
    $("#btn-add-widget a").on({click: function(){
            //creation du widget et sauvegarde dans labase de donnée
            console.log("coucou c'est moi !");
            widget_save(("#widget-grpe"),$("#center div[m-id='"+idmonitor+"'] div div.widget_zone"),$("#add-widget-name").val(), idmonitor);
            
            //Effacer la fenetre de creation
            $("#lightbox-add-widget div#shadowing").hide();
            $("#lightbox-add-widget div#box").hide();
            $("#lightbox-add-widget").bind("click");
            //désactiver l'evenement de la boite pour eviter les doublons'
            $(this).unbind("click");
    }});
}});


/* bouton widget suppression de l'element  */
$("a#widget-trash").live("click", function(){
    $('#modal-from-widget').bind('show').modal({backdrop: true});
    //console.log($(this).parent().parent().parent().attr('w-id'));
    var widgetid = $(this).parent().parent().parent().attr('w-id');
    var monitorid = $("#widget-grpe li.li_grey[w-id="+widgetid+"]").attr('m-id');
    console.log(monitorid);
    var json = '{"id": "'+widgetid+'"}';
    
    $("#delete-widget").on({click: function(){
            
        $.ajax({
                url: adress+"widget/delete",
                type:"POST",
                contentType: 'application/json',
                async: true,
                data: json,
                success:function (data) {
                    //Mise à jour de la page
                    $("#widget-grpe li.li_grey[w-id="+widgetid+"]").remove();
                    $("#center div.container_page[m-id="+monitorid+"] div div.widget_zone div[w-id="+widgetid+"]").remove();
                    $('#modal-from-widget').modal('hide');
                },
                error:function (xhr, ajaxOptions, thrownError){
                        alert(xhr.status);
                        alert(thrownError);
                }
        });
        //désactiver l'evenement de la boite pour eviter les doublons'
        $(this).unbind("click");
    }});
});

/* button widget reduce */
$("a[title='toggle']").live("click",function(){
    var widget_id = $(this).parent().parent().parent().attr("w-id");
    console.log(widget_id);
    widget_update(widget_id);
});

/* Button widget test */
/*
$("#widget_zone div div h4 a[title='toogle']").on({click: function (){
    var widget_id = $(this).;
}});*/

$("#widget_menu li.wiget_list div.btn").on({
        click: function(event){
                alert('div');
        }
});


/******************** init center button ******************************/

/* Boutton liste profile*/
//Save all widgets
$("#profile-list a[data-click='save']").on({click: function(){
        console.log("update des widgets.");
        $(".widget_zone div.widget").each(function(){
           //console.log($(this).attr('w-id'));
           widget_update($(this).attr('w-id'));
        });
}});

//Previous button :
//TODO : La récupération du nom se fera par la base de donnée
$("#previous-desktop").on({click: function(){
    if($("#previous-desktop").attr('class') != "disabled"){
        var max = $("#desktop-grpe li").length;
        //Initialisation de l'index du moniteur courrant apres deplacement
        indexCurrentDesktop = ((indexCurrentDesktop - 1) > 0) ? (indexCurrentDesktop - 1) : 0;
        var currentDesktop = $('#desktop-grpe li a').get(indexCurrentDesktop);
        //alert(listOfDesktop[0]);
        //On désactive le button si on arrive à la fin
        if(indexCurrentDesktop <= 0){
            $("#previous-desktop").attr('class','disabled');
        }

        //On active le button precédent
        if($("#next-desktop").attr('class') == "disabled" && indexCurrentDesktop < (max -1)){
            $("#next-desktop").attr('class','next');
        }
        //Mise à jour du label
        $("#label-desktop-name label").html($(currentDesktop).find("span").text());
        
        //mise à jour du menu deroulant et du bureau
        tabContainers = $('#center > div');
        tabContainers.hide().filter(currentDesktop.hash).show();
        
        $('#monitor_menu li.monitor_page a i.icon-ok').removeClass('icon-black');
        $('#monitor_menu li.monitor_page .icon-ok').addClass('icon-white');
        $(currentDesktop).children().children(".icon-ok").removeClass('icon-white');
        $(currentDesktop).children().children(".icon-ok").addClass('icon-black');
        
        //Show desktop's widget
        $("#widget_menu div li.li_grey").widget_show_by_monitor($(currentDesktop).parent().attr("m-id"));
    }
}});

//Next button : 
$("#next-desktop").on({click: function(){
    if($("#next-desktop").attr('class') != "disabled"){
        var max = $("#desktop-grpe li").length;
        //Initialisation de l'index du moniteur courrant apres deplacement
        indexCurrentDesktop = ((indexCurrentDesktop + 1) < (max + 1)) ? (indexCurrentDesktop + 1) : (max - 1) ;
        var currentDesktop = $('#desktop-grpe li a').get(indexCurrentDesktop);
        //On désactive le button si on arrive à la fin
        if(indexCurrentDesktop >= (max - 1)){
            $("#next-desktop").attr('class','disabled');
        }

        //On active le button precédent
        if($("#previous-desktop").attr('class') == "disabled" && indexCurrentDesktop > 0){
            $("#previous-desktop").attr('class','previous');
        }
        
        //Mise à jour du label centrale
        $("#label-desktop-name label").html($(currentDesktop).find("span").text());
        
        //mise à jour du menu deroulant et du bureau
        tabContainers = $('#center > div');
        tabContainers.hide().filter(currentDesktop.hash).show();
        $('#monitor_menu li.monitor_page a i.icon-ok').removeClass('icon-black');
        $('#monitor_menu li.monitor_page .icon-ok').addClass('icon-white');
        $(currentDesktop).children().children(".icon-ok").removeClass('icon-white');
        $(currentDesktop).children().children(".icon-ok").addClass('icon-black');
        
        //Show desktop's widget
        $("#widget_menu div li.li_grey").widget_show_by_monitor($(currentDesktop).parent().attr("m-id"));
    }
}});

//
$("#profile").on({click: function(){
        if($("#profile-list").css('display')=='none')
            $("#profile-list").css('display','block');
        else
            $("#profile-list").css('display','none');
}});


/************** MONITOR RADIOBOX **************/

var tabContainers;

//rang du bureau courant
var indexCurrentDesktop = 0;
//Liste des élements des bureau

//Gestionnaire d'evenement sur la liste des moniteurs mis en live pour rafraichissement automatique apres dom modification
$("#monitor_menu li.monitor_page a").live("click",
    function(){
        //Modification de l'index du bureau courant
        var max = $("#desktop-grpe li").length;
        for(var i = 0; i < max; i++){
            //console.log(this);
            //console.log($('#desktop-grpe li a').get(i));
            if (this === $('#desktop-grpe li a').get(i)){
                indexCurrentDesktop = i;
                //console.log(indexCurrentDesktop);
                break;
            }
        }
        
        //Modification sur la liste
        tabContainers = $('#center > div');
        tabContainers.hide().filter(this.hash).show();
        $('#monitor_menu li.monitor_page a i.icon-ok').removeClass('icon-black');
        $('#monitor_menu li.monitor_page .icon-ok').addClass('icon-white');
        $(this).children().children(".icon-ok").removeClass('icon-white');
        $(this).children().children(".icon-ok").addClass('icon-black');
        
        //Mise à jour des bouton de navigations latéral
        if(indexCurrentDesktop == 0)
            $("#previous-desktop").attr('class','disabled');
        
        if (indexCurrentDesktop >= (max - 1))
            $("#next-desktop").attr('class', 'disabled');
        
        if(indexCurrentDesktop > 0 && ($("#previous-desktop").attr('class') == "disabled"))
            $("#previous-desktop").attr('class','previous');
        
        if(indexCurrentDesktop < (max - 1) && ($("#next-desktop").attr('class') == "disabled"))
            $("#next-desktop").attr('class','next');
        
        //Mise à jour du label
        $("#label-desktop-name label").html($(this).find('span').text());
        
        //Show desktop's widget
        $("#widget_menu div li.li_grey").widget_show_by_monitor($(this).parent().attr("m-id"));
    }
).filter(':first').click().click();

//Create new monitor
$("#monitor_menu li.new-monitor a").on({click: function(){
        $("#lightbox-newmonitor div#shadowing").show();
        $("#lightbox-newmonitor div#box").show();
        $("#lightbox-newmonitor").unbind("click");
}});


//Bouton de la lightbox create monitor
$("#lightbox-newmonitor div#btn-create-desktop a").on({click: function(){
        
        var json = '{"monitor": "'+$("#new-monitor-name").val()+'","comment": "'+$("#new-monitor-cmt").val()+'"}';
        
        //TODO : Changer les addresses
        //Envoi des informations sur le nouveau moniteur
        $.ajax({
            url: adress+"monitor/save",
            type:"POST",
            contentType: 'application/json',
            async: true,
            data: json,
            dataType: 'json',
            success:function (data) {
                //Mise à jour du menu supérieur
                $("#desktop-grpe").monitor_add_menu($("#new-monitor-name").val(), data["id"]);
                $("#center").monitor_add_layout($("#new-monitor-name").val(), data["id"]);
                //Rafraichir sur le layout
                var selector = "#"+$("#new-monitor-name").val();
                $(selector).layout(layout_Outer_container);
                //TODO: Mise à jour de la liste de moniteur
                listOfDesktop = $.makeArray(document.getElementById('monitor_menu').getElementsByClassName('button-desktop-activate'));
                
                //TODO: Mise à jour de la base de donnée

                //TODO: Réinitiliser la div par default
                $("#new-monitor-name").val("New Desktop");
                $("#lightbox-newmonitor div#shadowing").hide();
                $("#lightbox-newmonitor div#box").hide();
                $("#lightbox-newmonitor").bind("click");
            },
            error:function (xhr, ajaxOptions, thrownError){
                    //alert(xhr.status);
                    //alert(thrownError);
                    alert("Vous avez déja un bureau du nom de "+$("#new-monitor-name").val());
            }
        });
}});


/**
 * Evenement sur le button suppression moniteur
 * TODO : Ajouter fenetre de confirmation de suppression
 * Solution fenetre de conformation : http://jsfiddle.net/MjmVr/3/
 */
$("#monitor_menu li.monitor_page a div div.btn i.icon-trash").live("click", function(){
    //alert("Suppression");
    //Extraction du nom du moniteur
    
    $('#modal-from-dom').bind('show').modal({backdrop: true});

    var tmp = $(this).parent().parent().parent().attr("href");
    var monitor_name = tmp.split("#")[1];
    var json = '{"monitor": "'+monitor_name+'"}';
    //console.log($(this).parent().parent().parent().parent());
    
    $("#delete-desktop").on({click: function(){
        $.ajax({
                url: adress+"monitor/delete",
                type:"POST",
                contentType: 'application/json',
                async:true,
                data: json,
                success:function (data) {
                    $('#modal-from-dom').modal('hide');
                    //Mise à jour de la page
                    var selector = "#monitor_menu li.monitor_page a[href$=#"+monitor_name+"]";
                    $(selector).remove();
                    $("#center div#"+monitor_name).remove();
                    var max = $("#desktop-grpe li").length;
                    var index = 0;
                    currentDesktop = $('#desktop-grpe li a').get(index);
                    //mise à jour du menu deroulant et du bureau
                    tabContainers = $('#center > div');
                    tabContainers.hide().filter(currentDesktop.hash).show();
                    $('#monitor_menu li.monitor_page a i.icon-ok').removeClass('icon-black');
                    $('#monitor_menu li.monitor_page .icon-ok').addClass('icon-white');
                    $(currentDesktop).children().children(".icon-ok").removeClass('icon-white');
                    $(currentDesktop).children().children(".icon-ok").addClass('icon-black');
                    
                    //Mise à jour des bouton de navigations latéral
                    if(index == 0)
                        $("#previous-desktop").attr('class','disabled');

                    if (index >= (max - 1))
                        $("#next-desktop").attr('class', 'disabled');

                    if(index > 0 && ($("#previous-desktop").attr('class') == "disabled"))
                        $("#previous-desktop").attr('class','previous');

                    if(index < (max - 1) && ($("#next-desktop").attr('class') == "disabled"))
                        $("#next-desktop").attr('class','next');

                    //Mise à jour du label
                    $("#label-desktop-name label").html($(this).find('span').text());
                    //console.log($(this).parent().parent().parent().attr("href"));
                    
                },
                error:function (xhr, ajaxOptions, thrownError){
                        alert(xhr.status);
                        alert(thrownError);
                }
        });
        //désactiver l'evenement de la boite pour eviter les doublons'
        $(this).unbind("click");
    }});
});


/**
 * Evenement sur le button modification moniteur
 * 
 */
$("#monitor_menu li.monitor_page a div div.btn i.icon-pencil").live("click", function(){
    //alert("Suppression");
    //Extraction du nom du moniteur
    $("#lightbox-update-monitor div#shadowing").show();
    $("#lightbox-update-monitor div#box").show();
    $("#lightbox-update-monitor").unbind("click");
    var tmp = $(this).parent().parent().parent().attr("href");
    var monitor_name = tmp.split("#")[1];
    
    //Evenement sur le bouton envoyer
    $("#btn-update-desktop a").on({click: function(){
       
        var json = '{"monitor": "'+monitor_name+'","newname": "'+$("#update-monitor-name").val()+'","newcomment": "'+$("#update-monitor-cmt").val()+'"}';
        
        $.ajax({
                url: adress+"monitor/update",
                type: "POST",
                contentType: 'application/json',
                async: true,
                data: json,
                success:function (data) {
                    //Mise à jour du menu supérieur
                    var selector = "#monitor_menu li.monitor_page a[href$=#"+monitor_name+"]";
                    $(selector).find('span').text($("#update-monitor-name").val());
                    $(selector).attr("href","#"+$("#update-monitor-name").val());
                    
                    //Mise à jour du conteneur
                    var selector = "#center div#"+monitor_name;
                    $(selector).attr("id",$("#update-monitor-name").val());

                    //TODO: Mise à jour de la base de donnée

                    //TODO: Réinitiliser la div par default
                    $("#update-monitor-name").val("New Desktop");
                    $("#lightbox-update-monitor div#shadowing").hide();
                    $("#lightbox-update-monitor div#box").hide();
                    $("#lightbox-update-monitor").bind("click");
                },
                error:function (xhr, ajaxOptions, thrownError){
                        alert(xhr.status);
                        alert(thrownError);
                }
        });
        //désactiver l'evenement de la boite pour eviter les doublons'
        $(this).unbind("click");
    }});
});
